package com.aliyun.heiyu.powermaster.server.rotary.utils;

import com.aliyun.heiyu.common.util.StringUtil;
import com.aliyun.heiyu.powermaster.server.rotary.object.transit.TemData;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 数据处理工具类
 * @Author shun.zhang
 * @Date 2019/12/5 16:20
 **/
public class IpcDataUtil {
    private static int DATA_LENGTH = 4;
    /**
     * @return String
     * @Author shun.zhang
     * @Description 将数据封装为数组传给工控机
     * @Date 17:31 2019/12/5
     * @Param String addr 设备地址
     * @Param String order 设备功能
     * @Param String modbusAddr modbus地址
     * @Param String count 个数
     **/
    public static String potData(String treaty, int addr, int order, int modbusAddr, double count) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(treaty)
            .append("://")
            .append(addr)
            .append("/")
            .append(order)
            .append("/")
            .append(modbusAddr)
            .append("/")
            .append(count);
        return buffer.toString();
    }

    /**
     * @return TemData temData
     * @Author shun.zhang
     * @Description 将工控机的数据转化为实体
     * @Date 17:30 2019/12/5
     * @Param String data
     **/
    public static TemData getData(String data) {
        if (StringUtil.isEmpty(data)) {
            return null;
        }
        /**字符串转为数组*/
        String[] datas = data.replace("]", "").replace("[", "").split(",");
        if (datas.length < DATA_LENGTH) {
            String data0 = datas[0];
            String data1 = datas[1];
            String data2 = datas[2];
            if (StringUtil.isEmpty(data0) && StringUtil.isEmpty(data1) && StringUtil.isEmpty(data2)) {
                //TODO 当返回全是0时  断定设置的值未在其范围
            }
            return null;
        }
        return getValue(datas);
    }

    /**
     * @return TemData 解析后的实体
     * @Author shun.zhang
     * @Description 读取数据
     * @Date 10:48 2019/12/18
     * @Param datas 解析的数组
     **/
    private static TemData getValue(String[] datas) {
        int modbusStart = Integer.parseInt(datas[2]);
        TemData temData = new TemData();
        Map<Integer, Double> value = new ConcurrentHashMap(100);
        temData.setDeviceAddr(Integer.parseInt(datas[0]));
        temData.setOrder(Integer.parseInt(datas[1]));
        temData.setModbusAddr(modbusStart);
        for (int i = 3; i < datas.length; i++) {
            value.put(modbusStart++, Double.parseDouble(datas[i]));
            temData.setValue(value);
        }
        return temData;
    }
}
